<html>
<body>
<canvas id="myCanvas" width="1200" height="800" style="border:5px solid #00fff0;"></canvas>
<div>尺寸：<span id="show"></span></div>
<button id="mmn">blue</button>
<button id="een">red</button>
<button id="ccb">green</button>
<button id="eraser">white</button>
<button id="small">-</button>
<button id="big">+</button>
</body>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
var abc = document.getElementById('mmn');
var def = document.getElementById('een');
var ghi = document.getElementById('ccb');
var eraser = document.getElementById('eraser');
var small = document.getElementById('small');
var big = document.getElementById('big');
var show = document.getElementById('show');

let size=1;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
const mobile = false; // 根据是否移动设备设置
let color='red';

function change(e){
  console.log(e.target.innerText);
  color=e.target.innerText;
}
function sizeChange(e){
  console.log(e.target.innerText);
  if(e.target.innerText==="+"){
     size++;
     show.innerText=size;
     }else if(size===1){
       return;
     }else{
       size--;
       show.innerText=size;
     }
}
function draw(e) {
  if (!isDrawing) return;
  ctx.beginPath();
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(e.offsetX, e.offsetY);
  ctx.strokeStyle = color;
  ctx.lineWidth = size;
  ctx.stroke();
  lastX = e.offsetX;
  lastY = e.offsetY;
  hue++;
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
}
 
function startPosition(e) {
  isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];
}
 
function endPosition(e) {
  isDrawing = false;
}
abc.addEventListener('click', change);
def.addEventListener('click', change);
ghi.addEventListener('click', change);
eraser.addEventListener('click', change);
small.addEventListener('click', sizeChange);
big.addEventListener('click', sizeChange);
canvas.addEventListener('mousedown', startPosition);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', endPosition);
 
// 移动设备触摸事件
canvas.addEventListener('touchstart', function(e) {
  e.preventDefault();
  isDrawing = true;
  const touch = e.touches[0];
  [lastX, lastY] = [touch.offsetX, touch.offsetY];
});
 
canvas.addEventListener('touchmove', function(e) {
  e.preventDefault();
  draw(e.touches[0]);
});
 
canvas.addEventListener('touchend', function(e) {
  e.preventDefault();
  isDrawing = false;
});
</script>
</html>
